import 'dart:convert';

import 'package:dart_date/dart_date.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:sprintf/sprintf.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/amap_poi.dart';
import 'package:yt_devops/model/install_provider_model.dart';
import 'package:yt_devops/model/user_model.dart';
import 'package:yt_devops/pages/tasks/task_list/task_list_controller.dart';

import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/task/task_services.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/constants/time_formated.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';

import 'create_install_task_model.dart';

class CreateInstallTaskController extends GetxController {
  CreateInstallTaskModel model = CreateInstallTaskModel();
  // 任务列表页
  TaskListController taskListController = Get.find();

  TaskServices services = Get.find();

  late FormGroup form;

  FormGroup buildForm() => fb.group(<String, Object>{
        'siteName': FormControl<String>(value: ''),
        'name': FormControl<String>(value: ''),
        'orgId': FormControl<InstallProviderModel>(
            validators: [Validators.required], value: getCurInstallProvider()),
        'map': FormControl<MapType>(
            validators: [Validators.required], value: MapType.amap),
        'handlerBy': FormControl<UserModel>(
          validators: [Validators.required],
        ),
        'userName': FormControl<String>(
          validators: [Validators.required],
        ),
        'phone': FormControl<String>(
          validators: [Validators.required],
        ),
        'remark': FormControl<String>(),
        'content': FormControl<String>(),
        'timeOfAppointment': FormControl<DateTime>(
          validators: [Validators.required],
        ),
        'address': FormControl<AmapPoi>(value: null),
        'descPicUrl': FormControl<List<String>>(value: []),
      });

  int? id;

  bool get isAdd => id == null ? true : false;

  String get title => id == null
      ? sprintf(
          ResKey.commonCreateSentence.tr, [ResKey.workOrderInstallOrder.tr])
      : sprintf(
          ResKey.commonEditSentence.tr, [ResKey.workOrderInstallOrder.tr]);

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null && Get.arguments['id'] != null) {
      id = Get.arguments['id'];
      loadDetail(id!);
    }
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  // 当是安装商登录时，则获取改用户的安装商信息，并回填
  InstallProviderModel? getCurInstallProvider() {
    if (UserEntityManager().roleID == RoleType.installer.value) {
      var user = UserEntityManager().userModel;
      return InstallProviderModel(
          orgId: user.orgId, orgName: user.org?.orgName);
    } else {
      return null;
    }
  }

  loadDetail(int id) => Configs.httpClient.requestWithLoading(() async {
        var params = {'id': id};
        var data = await services.getInstallTaskDetail(params);

        form.resetState({
          'siteName': ControlState<String>(
            value: data['siteName'],
          ),
          'name': ControlState<String>(
            value: data['name'],
          ),
          'orgId': ControlState<InstallProviderModel>(
            value: InstallProviderModel.fromJson(data),
          ),
          'handlerBy': ControlState<UserModel>(
            value: UserModel(
                userId: data['handlerBy'], userName: data['handlerName']),
          ),
          'userName': ControlState<String>(value: data['userName']),
          'phone': ControlState<String>(value: data['phone']),
          'remark': ControlState<String>(value: data['remark']),
          'content': ControlState<String>(value: data['content']),
          'timeOfAppointment': ControlState<DateTime>(
              value: DateTime.parse(data['timeOfAppointment']!)),
          'map': ControlState<MapType>(
              value: MapType.values.firstWhereOrNull(
                      (element) => element.value == data['map']) ??
                  MapType.amap),
          'address': ControlState<AmapPoi>(
            value: AmapPoi(
                formattedAddress: data['address'],
                latitude: data['latitude'] ?? 0,
                longitude: data['longitude'] ?? 0),
          ),
          'descPicUrl': ControlState<List<String>>(
              value: FuncUtils.isEmpty(data['descPicUrl'])
                  ? []
                  : data['descPicUrl'].split(','))
        });
        update();
      });

  Future<dynamic> Function(Map) getService() {
    if (isAdd) {
      return services.createInstall;
    } else {
      return services.editInstall;
    }
  }

  commit(FormGroup form) => Configs.httpClient.requestWithLoading(() async {
        if (!form.valid) {
          return;
        }
        var params = form.rawValue;
        var address = form.control('address').value;

        params
          ..putIfAbsent('longitude', () => address.longitude)
          ..putIfAbsent('latitude', () => address.latitude);
        params['map'] = (form.control('map').value as MapType).value;
        params['adcode'] = address.adcode;
        params['handlerName'] = form.control('handlerBy').value.userName;
        params['handlerId'] = form.control('handlerBy').value.userId;
        params['userName'] = form.control('userName').value;
        params['phone'] = form.control('phone').value;
        params['remark'] = form.control('remark').value;
        params['content'] = form.control('content').value;
        params['address'] = address.formattedAddress;
        params['handlerBy'] = form.control('handlerBy').value.userId;
        params['orgId'] = form.control('orgId').value.orgId;
        params['timeOfAppointment'] =
            (form.control('timeOfAppointment').value as DateTime)
                .format(TimeFormated.dateTimeFromated);
        params['descPicUrl'] = form.control('descPicUrl').value.join(',');
        if (isAdd == false) {
          params['id'] = id;
        }
        Log.d(jsonEncode(params));
        await getService()(params);
        EasyLoading.showSuccess(
          '${ResKey.submitSuccessTip.tr}! ',
        ).then((value) {
          taskListController.refreshInstall();
          Get.back(result: true);
        });
      });
}
